package vip.youngboy.longpoll.rest;

import com.google.common.eventbus.EventBus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import vip.youngboy.longpoll.service.ConfirmEvent;
import vip.youngboy.longpoll.service.LongPollService;
import vip.youngboy.longpoll.service.ScanEvent;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@RestController
@RequestMapping("/api")
public class LongPollRest {

    @Autowired
    private LongPollService longPollService;

    @Autowired
    private EventBus eventBus;


    @GetMapping("/longPolling")
    public void doPollingConfig(HttpServletRequest request, HttpServletResponse response,
                                @RequestParam String uuid,@RequestParam String type)
            throws IOException, ServletException {

        longPollService.addLongPollingClient(request, response, uuid, type);

    }

    @GetMapping("/scan/{uuid}")
    public ResponseEntity scanQrCode(@PathVariable String uuid){
        //这里需要认证用户的合法性
        eventBus.post(new ScanEvent(uuid));
        return ResponseEntity.ok("扫码成功，显示是否授权页面");
    }

    @GetMapping("/confirm/{uuid}")
    public ResponseEntity confirmAuth(@PathVariable String uuid,String result){
        //这里需要认证用户的合法性
        //TODO 认证成功需要带上code和state返回给客户端
        eventBus.post(new ConfirmEvent(uuid,result));
        return ResponseEntity.ok("确认授权");
    }

}
